<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          值班日期:
         <NDatePicker input-readonly style="width: 300rem" placeholder="请选择开始时间" clearable type="daterange"
            @update-formatted-value="handleFormattedStart" />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getDutyList())">
            查询
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
        <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VDialogContent @close="modalVisible = false" @submit="submit" :title="title">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定退勤吗？
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import { NSpace, NButton, NDataTable, NPagination, useMessage, NModal, NDatePicker } from 'naive-ui'
import { h, reactive, ref, watch, onMounted } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { DutyModel } from '@/api/duty'
import type { HttpResponse } from '@/utils/http'
import type { DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import router from '@/router'
import { useViewerStore } from '@/views/OA/Common/store'
import { format } from 'date-fns'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()
const modalVisible = ref(false)

const columns: DataTableColumns = [
  {
    title: '用户',
    key: 'userName',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '部门',
    key: 'deptName',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '值班日期',
    key: 'dutyDate',
    width: 120,
    align: useStore.isCenter
  },
  {
    title: '班次',
    key: 'shift',
    width: 80,
    align: useStore.isCenter,
    render({ shift }) {
      return shift == 'day' ? '白班' : '夜晚'
    }
  },
  {
    title: '出勤时间',
    key: 'attendanceTime',
    width: 120,
    align: useStore.isCenter
  },
  {
    title: '退勤时间',
    key: 'withdrawalTime',
    width: 120,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 120,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.attendanceTime ? 'none' : 'ilne-block' },
          onClick: async () => {
            dutyId.value = row.id
            title.value = '出勤提示'
            modalVisible.value = true
          }
        },
        {
          default: () => '出勤'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.withdrawalTime ? 'none' : 'ilne-block' },
          onClick: async () => {
            dutyId.value = row.id
            title.value = '退勤提示'
            modalVisible.value = true
          }
        },
        {
          default: () => '退勤'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: async () => {
            router.push({
              path: '/OA/Duty/SignDutyAdd',
              query: { id: row.id, flat: true as never }
            })
          }
        },
        {
          default: () => '补签申请'
        }
      )
    ]
  }
]
// 开始时间选择
const handleFormattedStart = (v: any) => {
  if (v) (paginationReactive.dutyStartTime = v[0]), (paginationReactive.dutyEndTime = v[1])
  else (paginationReactive.dutyStartTime = null), (paginationReactive.dutyEndTime = null)
}
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  dutyStartTime: null, //开始时间
  dutyEndTime: null, //结束时间
  onChange: (page: number) => {
    paginationReactive.page = page
    getDutyList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getDutyList()
  }
})
// 提交
const title = ref()
const dutyId = ref()
const submit = async () => {
  if (title.value == '出勤提示') return attendance()
  withdrawal()
}
// 出勤
const attendance = async () => {
  modalVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<DutyModel>>({
    module: 'duty',
    api: 'dutyAttendance',
    override: {
      data: {
        attendanceTime: format(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        id: dutyId.value
      }
    }
  })
  if (error) return message.error('出勤失败'), (tableLoading.value = false)
  if (res.code !== 0) return message.error('出勤失败'), (tableLoading.value = false)
  getDutyList()
  message.success('出勤成功')
}
// 退勤
const withdrawal = async () => {
  modalVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<DutyModel>>({
    module: 'duty',
    api: 'dutyAttendance',
    override: {
      data: {
        withdrawalTime: format(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        id: dutyId.value
      }
    }
  })
  if (error) return message.error('退勤失败'), (tableLoading.value = false)
  if (res.code !== 0) return message.error('退勤失败'), (tableLoading.value = false)
  getDutyList()
  message.success('退勤成功')
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getDutyList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<DutyModel>>({
    module: 'duty',
    api: 'dutyList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        dutyStartTime: paginationReactive.dutyStartTime,
        dutyEndTime: paginationReactive.dutyEndTime
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = []
  setTimeout(() => {
    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  }, 0)
}

onMounted(() => { 
  getDutyList()
 })
</script>
<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
